<template>
<div>
  <el-dialog
    :title="title"
    :close-on-click-modal="false"
     v-dialogDrag
    :visible.sync="visible">
    <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"  :disabled="method==='view'"
             label-width="120px">
      <el-row  :gutter="15">
        <el-col :span="12">
            <el-form-item label="车牌号" prop="licensePlateNumber"
                :rules="[
                  {required: true, message:'车牌号不能为空', trigger:'blur'}
                 ]">
              <el-input v-model="inputForm.licensePlateNumber" placeholder="请填写车牌号"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="商家" prop="merchant.id"
                :rules="[
                  {required: true, message:'商家ID不能为空', trigger:'blur'}
                 ]">
          <GridSelect
            title="选择商家ID"
            labelName = 'merchantName'
            labelValue = 'id'
            :value = "inputForm.merchant.id"
            :limit="1"
            @getValue='(value) => {inputForm.merchant.id=value}'
            :columns="[
            {
              prop: 'id',
              label: '主键'
            },
            {
              prop: 'merchantName',
              label: '商家名称'
            },
            {
              prop: 'storePicture',
              label: '店铺图片'
            },
            {
              prop: 'storeAddress',
              label: '店铺地址'
            }
            ]"
            :searchs="[
            {
              prop: 'merchantName',
              label: '商家名称'
            },
            {
              prop: 'storeAddress',
              label: '店铺地址'
            }
            ]"
            dataListUrl="/vmerchantinformation/vMerchantInformation/list"
            entityBeanName="vMerchantInformation"
            queryEntityUrl="/vmerchantinformation/vMerchantInformation/queryById">
          </GridSelect>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="发放人" prop="lssuedBy.id"
                :rules="[
                  {required: true, message:'发放人（员工）ID不能为空', trigger:'blur'}
                 ]">
          <GridSelect
            title="选择发放人（员工）ID"
            labelName = 'fullName'
            labelValue = 'id'
            :value = "inputForm.lssuedBy.id"
            :limit="1"
            @getValue='(value) => {inputForm.lssuedBy.id=value}'
            :columns="[
            {
              prop: 'id',
              label: '主键'
            },
            {
              prop: 'fullName',
              label: '员工姓名'
            },
            {
              prop: 'cellphoneNumber',
              label: '员工手机号'
            }
            ]"
            :searchs="[
            {
              prop: 'fullName',
              label: '员工姓名'
            },
            {
              prop: 'cellphoneNumber',
              label: '员工手机号'
            }
            ]"
            dataListUrl="/vmerchantstaff/vMerchantStaff/list"
            entityBeanName="vMerchantStaff"
            queryEntityUrl="/vmerchantstaff/vMerchantStaff/queryById">
          </GridSelect>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="角色类型" prop="roleType"
                :rules="[
                  {required: true, message:'角色类型（0：商家，1：员工）不能为空', trigger:'blur'}
                 ]">
                <el-select v-model="inputForm.roleType" placeholder="请选择"  style="width: 100%;">
                          <el-option  label="商家" value="0"> </el-option>
                          <el-option  label="员工" value="1"> </el-option>
                      </el-select>
           </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
            <el-form-item label="礼品ID" prop="gift.id"
                :rules="[
                  {required: true, message:'礼品ID不能为空', trigger:'blur'}
                 ]">
          <GridSelect
            title="选择礼品ID"
            labelName = 'giftName'
            labelValue = 'id'
            :value = "inputForm.gift.id"
            :limit="1"
            @getValue='(value) => {inputForm.gift.id=value}'
            :columns="[
            {
              prop: 'id',
              label: '主键'
            },
            {
              prop: 'giftName',
              label: '礼品名称'
            },
            {
              prop: 'giftPicture',
              label: '礼品图片'
            },
            {
              prop: 'stock',
              label: '库存'
            }
            ]"
            :searchs="[
            {
              prop: 'giftName',
              label: '礼品名称'
            },
            {
              prop: 'stock',
              label: '库存'
            }
            ]"
            dataListUrl="/vgiftinformation/vGiftInformation/list"
            entityBeanName="vGiftInformation"
            queryEntityUrl="/vgiftinformation/vGiftInformation/queryById">
          </GridSelect>
           </el-form-item>
        </el-col> -->
        <el-col :span="12">
            <el-form-item label="礼品名称" prop="giftName"
                :rules="[
                 ]">
              <el-input v-model="inputForm.giftName" placeholder="请填写礼品名称"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="24">
            <el-form-item label="礼品图片" prop="giftPicture"
                :rules="[
                  {required: true, message:'礼品图片不能为空', trigger:'blur'}
                 ]">
              <el-upload ref="giftPicture"
              v-if="visible"
              list-type="picture-card"
                    :action="`${this.$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/vgiftdistributionrecord/vGiftDistributionRecord`"
                    :headers="{token: $cookie.get('token')}"
                    :on-preview="(file, fileList) => {
                      showImg(inputForm.giftPicture)
                    }"
                    :on-success="(response, file, fileList) => {
                       inputForm.giftPicture = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
                    }"
                    :on-remove="(file, fileList) => {
                      $http.post(`/sys/file/webupload/deleteByUrl?url=${(file.response && file.response.url) || file.url}`).then(({data}) => {
                        $message.success(data.msg)
                      })
                      inputForm.giftPicture = fileList.map(item => item.url).join('|')
                    }"
                    :before-remove="(file, fileList) => {
                      return $confirm(`确定移除 ${file.name}？`)
                    }"
                    multiple
                    :limit="5"
                    :on-exceed="(files, fileList) =>{
                      $message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
                    }"
                    :file-list="giftPictureArra">
                    <i class="el-icon-plus"></i>
                  </el-upload>
           </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="现场图片" prop="sitePhotos"
                        :rules="[{required: true, message:'现场图片不能为空', trigger:'blur'}]">
            <el-upload ref="sitePhotos"
                       v-if="visible"
                       list-type="picture-card"
                       :action="`${this.$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/vgiftreceiverecord/vGiftReceiveRecord`"
                       :headers="{token: $cookie.get('token')}"
                       :on-preview="(file, fileList) => {
                        showImg(inputForm.sitePhotos)
                    }"
                       :on-success="(response, file, fileList) => {
                       inputForm.sitePhotos = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
                    }"
                       :on-remove="(file, fileList) => {
                      $http.post(`/sys/file/webupload/deleteByUrl?url=${(file.response && file.response.url) || file.url}`).then(({data}) => {
                        $message.success(data.msg)
                      })
                      inputForm.sitePhotos = fileList.map(item => item.url).join('|')
                    }"
                       :before-remove="(file, fileList) => {
                      return $confirm(`确定移除 ${file.name}？`)
                    }"
                       multiple
                       :limit="5"
                       :on-exceed="(files, fileList) =>{
                      $message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
                    }"
                       :file-list="sitePhotosArra">
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
            <el-form-item label="礼品详情" prop="giftDetails"
                :rules="[
                  {required: true, message:'礼品详情不能为空', trigger:'blur'}
                 ]">
            <WangEditor ref="giftDetailsEditor" v-model="inputForm.giftDetails"/>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="发放时间" prop="lssuingTime"
                :rules="[
                 ]">
                <el-date-picker
                      style="width: 100%;"
                      v-model="inputForm.lssuingTime"
                      type="datetime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      placeholder="选择日期时间">
                    </el-date-picker>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="领取方式" prop="collectionMethod"
                :rules="[
                 ]">
              <el-input v-model="inputForm.collectionMethod" placeholder="请填写领取方式"     ></el-input>
           </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="发放状态" prop="distributionStatus"
                :rules="[
                 ]">
                <el-select v-model="inputForm.distributionStatus" placeholder="请选择"  style="width: 100%;">
                          <el-option  label="用户未领取" value="0"> </el-option>
                          <el-option  label="发放成功" value="1"> </el-option>
                      </el-select>
           </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
            <el-form-item label="备注信息" prop="remarks"
                :rules="[
                 ]">
          <el-input type="textarea" v-model="inputForm.remarks" placeholder="请填写备注信息"     ></el-input>
           </el-form-item>
        </el-col> -->
        </el-row>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" v-if="method != 'view'" @click="doSubmit()" v-noMoreClick>确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  import GridSelect from '@/components/gridSelect'
  import WangEditor from '@/components/editor/WangEditor'
  export default {
    data () {
      return {
        title: '',
        method: '',
        visible: false,
        loading: false,
        giftPictureArra: [],
        sitePhotosArra: [],
        inputForm: {
          id: '',
          licensePlateNumber: '',
          merchant: {
            id: ''
          },
          lssuedBy: {
            id: ''
          },
          roleType: '',
          gift: {
            id: ''
          },
          giftName: '',
          giftPicture: '',
          giftDetails: '',
          lssuingTime: '',
          collectionMethod: '',
          distributionStatus: '',
          remarks: ''
        }
      }
    },
    components: {
      GridSelect,
      WangEditor
    },
    methods: {
      showImg(imgStrList) {
      var imgList = imgStrList.split("|");
      this.$hevueImgPreview({
        multiple: true,
        nowImgIndex: 0,
        imgList: imgList,
      });
    },
      init (method, id) {
        this.method = method
        this.inputForm.id = id
        if (method === 'add') {
          this.title = `新建礼品发放记录列表`
        } else if (method === 'edit') {
          this.title = '修改礼品发放记录列表'
        } else if (method === 'view') {
          this.title = '查看礼品发放记录列表'
        }
        this.giftPictureArra = []
        this.sitePhotosArra = []
        this.visible = true
        this.loading = false
        this.$nextTick(() => {
          this.$refs.inputForm.resetFields()
          this.$refs.giftDetailsEditor.init('')
          if (method === 'edit' || method === 'view') { // 修改或者查看
            this.loading = true
            this.$http({
              url: `/vgiftdistributionrecord/vGiftDistributionRecord/queryById?id=${this.inputForm.id}`,
              method: 'get'
            }).then(({data}) => {
              this.inputForm = this.recover(this.inputForm, data.vGiftDistributionRecord)
              this.$refs.giftDetailsEditor.init(this.inputForm.giftDetails)
              this.inputForm.giftPicture.split('|').forEach((item) => {
                if (item.trim().length > 0) {
                  this.giftPictureArra.push({name: decodeURIComponent(item.substring(item.lastIndexOf('/') + 1)), url: item})
                }
              })
              this.inputForm.sitePhotos.split('|').forEach((item) => {
              if (item.trim().length > 0) {
                this.sitePhotosArra.push({
                  name: decodeURIComponent(item.substring(item.lastIndexOf('/') + 1)),
                  url: item
                })
              }
            })
              this.loading = false
            })
          }
        })
      },
      // 表单提交
      doSubmit () {
        this.$refs['inputForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            this.$http({
              url: `/vgiftdistributionrecord/vGiftDistributionRecord/save`,
              method: 'post',
              data: this.inputForm
            }).then(({data}) => {
              this.loading = false
              if (data && data.success) {
                this.visible = false
                this.$message.success(data.msg)
                this.$emit('refreshDataList')
              }
            })
          }
        })
      }
    }
  }
</script>